package com.gcosc.hly.codejava.Utils;

import com.gcosc.hly.codejava.exception.BusinessException;
import com.gcosc.hly.codejava.exception.SystemException;
import com.gcosc.hly.codejava.result.Code;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

@Log4j2
@Component
public class Base64Utils {

    @Autowired
    PathUtils pathUtils;

    // 对字节数组字符串进行Base64解码并生成图片
    //imgFilePath 待保存的本地路径
    public String GenerateImage(String base64Str, String imgFilePath) {
        if (StringUtils.isEmpty(base64Str)) // 图像数据为空
            throw new BusinessException(Code.BUSINESS_ERR, "图片不能为空");
        try {
            base64Str = base64Str.substring(base64Str.indexOf(",", 1) + 1, base64Str.length());
            // Base64解码
            byte[] bytes = Base64.decodeBase64(base64Str);

            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }

            //解析图片后缀名
            String type = checkImageBase64Format(bytes);
            if (type.equals("")){
                throw new BusinessException(Code.BUSINESS_ERR, "不支持文件类型");
            }

            //生成图片名称
            String name = UUID.randomUUID().toString();

            //判断储存路劲存不存在，不存在就创建文件夹
            FileUtils.file(pathUtils.path + pathUtils.imagesPath + imgFilePath);

            imgFilePath = pathUtils.imagesPath + imgFilePath + "\\" + name + "." + type;

            // 生成图片pathUtils
            OutputStream out = new FileOutputStream(pathUtils.path + imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return imgFilePath.replace("\\", "/");
        } catch (IOException e) {
            throw new SystemException(Code.SYSTEM_ERR, e.getMessage());
        }
    }

    public String checkImageBase64Format(String base64Str) {
        base64Str = base64Str.substring(base64Str.indexOf(",", 1) + 1, base64Str.length());
        byte[] b = Base64.decodeBase64(base64Str);
        return checkImageBase64Format(b);
    }

    public String checkImageBase64Format(byte[] b) {
        String type = "";
        if (0x424D == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "bmp";
        } else if (0x8950 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "png";
        } else if (0xFFD8 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = "jpg";
        }
        return type;
    }
}
